/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import React, {Component, PropTypes} from 'react';
import {createContainer} from 'meteor/react-meteor-data';
import {Users} from '../api/users/users.js';
import {UserCert} from '../api/user_cert/user_cert.js';
import {browserHistory} from 'react-router';
import {Session} from 'meteor/session';
import {Meteor} from 'meteor/meteor';

import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import Toggle from 'material-ui/Toggle';
import DatePicker from 'material-ui/DatePicker';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Chip from 'material-ui/Chip';
import Snackbar from 'material-ui/Snackbar';
import SvgIconErr from 'material-ui/svg-icons/alert/error';
import SvgIconCheck from 'material-ui/svg-icons/toggle/check-box';
import {blue400, blue300, red700, green700} from 'material-ui/styles/colors';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import IconButton from 'material-ui/IconButton';
import NavigationLeft from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import ActionAccountCircle from 'material-ui/svg-icons/action/account-circle';
import ActionDownload from 'material-ui/svg-icons/file/file-download';
import ActionEdit from 'material-ui/svg-icons/image/edit';
import Dialog from 'material-ui/Dialog';
import Tab1List from './Tab1List.jsx';
import Divider from 'material-ui/Divider';
import Avatar from 'material-ui/Avatar';
import db from "../DBStore/db";
import {KEYUTIL, X509, zulutodate} from 'jsrsasign';
import {Buffer} from "buffer";
import {GenCertificateWithPemPrvKey, VerifyPrvKeyWithPass} from "../api/cryptoHelper";

let QRCode = require('qrcode.react');

const styles = {
    root: {
        display: 'flex',
        flexWrap: 'wrap',
    },
    list: {
        margin: 15,
    },
    toolbar: {
        position: 'fixed',
        top: 0,
        width: '100%',
    },
}

// Task component - represents a single todo item
export class Tab2Detail extends Component {
    constructor(props) {
        super(props);

        this.state = {
            expanded: false,
            openHistory: false,
            openHistoryAll: false,
            openAccount: false,

            openCert: false,
            editUserInfo: false,
            checkPass: false,
            confirmUserInfo: false,
            snack_bar: false,
            snack_status: false,
            updateRes: '',
            new_name: '',
            new_name_err: '',
            new_phone: '',
            new_phone_err: '',
            new_email: '',
            new_email_err: '',
            new_address: '',
            new_address_err: '',
            new_unit: '',
            new_unit_err: '',
            new_err: '',
            update_pass: '',
            pass_err: '',


            mod_pass: false,
            old_pass: '',
            old_pass_err: '',
            new_pass1: '',
            new_pass1_err: '',
            new_pass2: '',
            new_pass2_err: '',

            cert: '',
        };
    }

    handleExpandChange(expanded) {
        const {editUserInfo} = this.state;
        this.setState({expanded: expanded});
        if (!expanded)
            this.setState({editUserInfo: false})
    };

    handleToggle(event, toggle) {
        this.setState({expanded: toggle});
    };

    handleExpand() {
        this.setState({expanded: true});
    };

    handleReduce() {
        this.setState({expanded: false});
    };

    //登录验证
    componentWillMount() {
        if (Session.get('curUser') === 'none') {
            browserHistory.push('/login');
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (Session.get('curUser') === 'none') {
            browserHistory.push('/login');
        }
    }

    componentDidMount(x, y, z) {
        this.setState({cw: window.innerWidth, ch: window.innerHeight});
    }

    handleClose() {
        this.setState({openHistory: false});
    }

    handleCloseAll() {
        this.setState({openHistoryAll: false});
    }

    handleModPwd() {
        const {mod_pass, snack_bar, snack_status, updateRes, old_pass, new_pass1, new_pass2} = this.state;
        this.setState({mod_pass: false});
        if (old_pass == '' || new_pass1 == '' || new_pass2 == '')
            this.setState({snack_status: false, updateRes: '有密码为空项', snack_bar: true});
        if (new_pass1 != new_pass2)
            this.setState({snack_status: false, updateRes: '两次密码不一样', snack_bar: true});
        if (!VerifyPrvKeyWithPass(this.props.openItem.prv_key_pem_encrypted, old_pass)) {
            this.setState({snack_status: false, updateRes: '原密码不对', snack_bar: true});
        } else {
            let new_prv_key_pem_encrypted = KEYUTIL.getKey(this.props.openItem.prv_key_pem_encrypted, old_pass);
            let prv_key_pem_encrypted = KEYUTIL.getPEM(new_prv_key_pem_encrypted, 'PKCS8PRV', new_pass1);
            db.table('users').update(this.props.openItem.id, {prv_key_pem_encrypted: prv_key_pem_encrypted}).then((id) => {
                this.setState({new_pass1: ''});
                this.setState({new_pass2: ''});
                this.setState({old_pass: ''});
                this.setState({snack_status: true, updateRes: '密码更新成功，稍后请重新登录!'});
                this.setState({snack_bar: true});
                //修改成功用户需要重新登录
                setTimeout(()=>{
                    browserHistory.push('/login')
                },3000)
            })
        }
    }

    onUpdateUserInfo() {
        const {snack_status, updateRes, snack_bar, update_pass, editUserInfo, checkPass, new_name, new_phone, new_email, new_unit, new_address} = this.state;
        const userInfo = {
            name: new_name,
            phone: new_phone,
            address: new_address,
            unit: new_unit,
            email: new_email,
        }
        this.setState({checkPass: !checkPass, editUserInfo: !editUserInfo})
        let curUser = Session.get('curUser');
        if (VerifyPrvKeyWithPass(curUser.prv_key_pem_encrypted, update_pass)) {
            let prv_key_pem_encrypted = curUser.prv_key_pem_encrypted;
            let user_cert_pem = GenCertificateWithPemPrvKey(update_pass, userInfo, prv_key_pem_encrypted)
            userInfo['user_certificate_pem'] = user_cert_pem;
            db.table('users').update(curUser.id, userInfo).then((id) => {
                db.table('users').where({phone: userInfo.phone}).first().then((res) => {
                    if (res) {
                        //修改数据库表user_cert,
                        Session.set('curUser', res)
                        this.setState({updateRes: '修改成功，请将证书提交给管理员确认！', snack_status: true})
                    } else {
                        this.setState({updateRes: '修改失败，请稍后重试！', snack_status: false})
                    }
                })
            }).catch(reason => {
                this.setState({updateRes: reason, snack_status: false})
            });
            this.setState({snack_bar: true})
        }
    }

    renderAppBar() {
        if (this.props.handleClose) {
            return (
                <AppBar title="账号详细"
                        iconElementLeft={
                            <IconButton
                                onTouchTap={this.props.handleClose}
                                iconStyle={{width: 48, height: 48}}
                                style={{padding: 0,}}
                            ><NavigationLeft/></IconButton>}
                />
            );
        } else
            return '';
    }

    renderCreateBy() {
        if (this.state.createdBy)
            return (
                <Tab2Detail
                    openItem={this.state.createdBy}
                    handleClose={this.handleCloseAccount.bind(this)}
                />
            );
        else return '';
    }

    renderMyCert() {
        let certdoc = this.state.cert;
        const user = Session.get('curUser');
        if (this.state.openCert)
            return (
                <div id='user_certificate' style={{height: this.state.ch, overflowY: 'auto', wordWrap: 'break-word'}}>
                    <AppBar title="我的证书"
                            style={styles.toolbar}
                            iconElementLeft={
                                <IconButton
                                    onTouchTap={() => {
                                        this.setState({openCert: !this.state.openCert})
                                    }}
                                    iconStyle={{width: 48, height: 48}}
                                    style={{padding: 0,}}
                                ><NavigationLeft/></IconButton>
                            }
                    />
                    <h2 style={{marginTop: 80, textAlign: 'center'}}>用户证书</h2>
                    <List style={styles.list}>
                        <Subheader>基本信息</Subheader>
                        <ListItem primaryText={'状态：' + '已通过审核 进入Repchain区块链平台'}/>
                        <ListItem primaryText={'序列号： ' + user.account_address}/>
                        <ListItem primaryText={'签名算法： ' + certdoc.signature_algorithm}/>
                        <ListItem primaryText={'颁发机构： ' + 'Repchain'}/>
                        <ListItem primaryText={'有效期截止至： '}
                                  secondaryText={certdoc.not_after.toString()}/>
                        <ListItem primaryText={'姓名: ' + user.name + ',' + '手机: ' + user.phone + ',' +
                                  '邮箱: ' + user.email + ',' + '通讯地址: ' + user.address}/>
                        <ListItem primaryText={'签名信息: ' + certdoc.signature}/>
                    </List>
                </div>
            )

        else return '';
    }

    renderChip() {
        let avatar_color = !this.state.snack_status ? red700 : green700;
        let avatar_icon = !this.state.snack_status ? <SvgIconErr/> : <SvgIconCheck/>;
        return (
            <Chip style={{top: 25,}} onClick={() => {
                this.setState({snackbar_open: false});
            }}>
                <Avatar color={avatar_color} icon={avatar_icon}/>
                {this.state.updateRes}
            </Chip>
        );
    }

    renderModPwd() {
        const user = Session.get('curUser');
        if (this.state.mod_pass) {
            const {mod_pass, old_pass, old_pass_err, new_pass1, new_pass2, new_pass1_err, new_pass2_err} = this.state;
            const actions_new = [
                <RaisedButton
                    label='确认'
                    style={{margin: 12}}
                    onTouchTap={(event) => {
                        this.setState({mod_success: ''});
                        this.handleModPwd();
                    }}
                />,
                <RaisedButton
                    label='取消'
                    style={{margin: 12}}
                    primary={true}
                    onTouchTap={(event) => {
                        this.setState({mod_pass: false})
                    }}
                />,
            ];
            return (
                <div>
                    <Dialog
                        title='修改密码'
                        actions={actions_new}
                        modal={false}
                        contentStyle={{width: '94%', height: 'auto'}}
                        open={mod_pass}
                        onRequestClose={(close) => {
                            this.setState({mod_pass: close})
                        }}
                        autoScrollBodyContent={true}
                    >
                        <TextField
                            type='password'
                            hintText='原始密码'
                            floatingLabelStyle={{color: blue300}}
                            floatingLabelText='原始密码'
                            defaultValue={old_pass}
                            errorText={old_pass_err}
                            style={{marginLeft: '5%', width: '90%'}}
                            onChange={(e, newValue) => {
                                const old_pass1 = newValue;
                                if (old_pass1 == '')
                                    this.setState({old_pass: old_pass1, old_pass_err: '密码不可为空'});
                                else
                                    this.setState({old_pass: old_pass1, old_pass_err: ''});
                            }}
                        /><br/>
                        <TextField
                            type='password'
                            hintText='新密码'
                            floatingLabelStyle={{color: blue300}}
                            floatingLabelText='新密码'
                            errorText={new_pass1_err}
                            style={{marginLeft: '5%', width: '90%'}}
                            onChange={(e, newValue) => {
                                const new_pass = newValue;
                                if (new_pass == '')
                                    this.setState({new_pass1: new_pass, new_pass1_err: '密码不可为空'});
                                else if (new_pass == old_pass)
                                    this.setState({new_pass1_err: '新密码和原密码需不一样'});
                                else
                                    this.setState({new_pass1: new_pass, new_pass1_err: ''});
                                if (new_pass2 != '' && new_pass2 != new_pass)
                                    this.setState({new_pass1_err: '密码不一致'});

                                if(!/^[A-Za-z0-9]{6,20}$/.test(new_pass)){
                                    this.setState({new_pass1: new_pass, new_pass1_err: '密码规则：6-20位字母或数字组合'});
                                }
                                //else
                                //this.setState({new_pass1_err: ''});
                            }}
                        /><br/>
                        <TextField
                            type='password'
                            hintText='新密码确认'
                            floatingLabelStyle={{color: blue300}}
                            floatingLabelText='新密码确认'
                            errorText={new_pass2_err}
                            style={{marginLeft: '5%', width: '90%'}}
                            onChange={(e, newValue) => {
                                const new_pass = newValue;
                                if (new_pass == '')
                                    this.setState({new_pass2: new_pass, new_pass2_err: '密码不可为空'});
                                else if (new_pass != new_pass1)
                                    this.setState({new_pass2: new_pass, new_pass2_err: '密码不一致'});
                                else if(new_pass == new_pass1)
                                    this.setState({new_pass2: new_pass, new_pass2_err: '', new_pass1_err: ''});
                            }}
                        /><br/>
                    </Dialog>
                </div>
            );
        } else
            return '';
    }


    render() {
        let item = this.props.openItem || {};
        const {
            snack_bar, checkPass, update_pass, pass_err, confirmUserInfo, editUserInfo, new_address, new_address_err, new_email, new_email_err, new_name, new_name_err, new_phone,
            new_phone_err, new_unit, new_unit_err, mod_pass, cert
        } = this.state;
        const actionUserInfo = [
            <FlatButton
                label="确认修改"
                primary={this.state.confirmUserInfo}
                disabled={!this.state.confirmUserInfo}
                onClick={this.onUpdateUserInfo.bind(this)}
            />,
            <FlatButton
                label="取消"
                primary={true}
                keyboardFocused={true}
                onClick={() => this.setState({checkPass: false})}
            />,
        ];
        let submitUserInfoEnable = (new_name != item.name && new_name_err == '' && new_name != '') ||
            (new_phone != item.phone && new_phone_err == '' && new_phone != '') ||
            (new_email != item.email && new_email_err == '' && new_email != '') ||
            (new_unit != item.unit && new_unit_err == '' && new_unit != '') ||
            (new_address != item.address && new_address_err == '' && new_address != '');
        return (
            <div>
                {this.renderAppBar()}
                <Card expanded={this.state.expanded}
                      containerStyle={{marginLeft: '5%', marginRight: '5%'}}
                      onExpandChange={this.handleExpandChange.bind(this)}>
                    <CardHeader
                        title={item.name}
                        subtitle={'TEL: ' + item.phone}
                        avatar={item.avatar}
                        actAsExpander={true}
                        showExpandableButton={true}

                    />
                    <CardText expandable={true} style={{height: '435px'}}>
                        <FlatButton
                            style={{float: 'right'}}
                            label="修改个人信息"
                            labelPosition="before"
                            primary={true}
                            icon={<ActionEdit/>}
                            onClick={(e) => {
                                this.setState({editUserInfo: !editUserInfo});
                                if (!editUserInfo) {
                                    this.setState({
                                        new_name: item.name,
                                        new_phone: item.phone,
                                        new_email: item.email,
                                        new_unit: item.unit,
                                        new_address: item.address
                                    })
                                }
                            }}
                        />
                        <TextField
                            floatingLabelText='姓名'
                            floatingLabelFixed={true}
                            floatingLabelStyle={{color: blue300}}
                            errorText={new_name_err}
                            fullWidth={true}
                            disabled={!editUserInfo}
                            defaultValue={item.name ? item.name : ''}
                            onChange={(e, newValue) => {
                                const name = newValue;
                                if (name === '')
                                    this.setState({new_name: name, new_name_err: '姓名不能为空！'})
                                else
                                    this.setState({new_name: name, new_name_err: ''})
                            }}
                        />
                        <TextField
                            floatingLabelText='手机'
                            floatingLabelStyle={{color: blue300}}
                            floatingLabelFixed={true}
                            errorText={new_phone_err}
                            fullWidth={true}
                            disabled={!editUserInfo}
                            defaultValue={item.phone ? item.phone : ''}
                            onChange={(e, newValue) => {
                                const phone = newValue;
                                if (phone === '')
                                    this.setState({new_phone: phone, new_phone_err: '手机号不能为空！'})
                                else if(/^13[0-9]{1}[0-9]{8}|15[0-9]{1}[0-9]{8}|18[0-9]{1}[0-9]{8}$/.test(phone))
                                    this.setState({new_phone: phone, new_phone_err: ''})
                                else
                                    this.setState({new_phone: phone, new_phone_err: '手机号格式不对'})

                                db.table('register_user').where({phone: phone}).first().then((res) => {
                                   if(res){
                                       if(phone != item.phone){
                                           this.setState({new_phone: phone, new_phone_err: '手机号已被注册'})
                                       }
                                   }
                                }).catch(e=>{
                                    console.log(e)
                                })
                            }}
                        />
                        <TextField
                            floatingLabelText='邮箱'
                            floatingLabelFixed={true}
                            floatingLabelStyle={{color: blue300}}
                            errorText={new_email_err}
                            fullWidth={true}
                            disabled={!editUserInfo}
                            defaultValue={item.email ? item.email : ''}
                            onChange={(e, newValue) => {
                                const email = newValue;
                                if (email === '')
                                    this.setState({new_email: email, new_email_err: '邮箱不能为空！'})
                                else if(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(email))
                                    this.setState({new_email: email, new_email_err: ''})
                                else
                                    this.setState({new_email: email, new_email_err: '邮箱格式错误！'})
                            }}
                        />
                        <TextField
                            floatingLabelText='工作单位'
                            floatingLabelFixed={true}
                            floatingLabelStyle={{color: blue300}}
                            errorText={new_unit_err}
                            fullWidth={true}
                            disabled={!editUserInfo}
                            defaultValue={item.unit ? item.unit : ''}
                            onChange={(e, newValue) => {
                                const unit = newValue;
                                if (unit === '')
                                    this.setState({new_unit: unit, new_unit_err: '工作单位不能为空！'})
                                else
                                    this.setState({new_unit: unit, new_unit_err: ''})
                            }}
                        />
                        <TextField
                            floatingLabelText='通讯地址'
                            floatingLabelStyle={{color: blue300}}
                            floatingLabelFixed={true}
                            errorText={new_address_err}
                            fullWidth={true}
                            disabled={!editUserInfo}
                            defaultValue={item.address ? item.address : ''}
                            onChange={(e, newValue) => {
                                const address = newValue;
                                if (address === '')
                                    this.setState({new_address: address, new_address_err: '住址不能为空！'})
                                else
                                    this.setState({new_address: address, new_adderss_err: ''})
                            }}
                        />
                        {editUserInfo ? <RaisedButton
                            style={{float: 'right', margin: '12px'}}
                            label="取消"
                            labelPosition="before"
                            primary={true}
                            onClick={(e) => {
                                this.setState({editUserInfo: false});
                            }}
                        /> : null}
                        {editUserInfo ? <RaisedButton
                            style={{float: 'right', margin: '12px'}}
                            label="提交"
                            labelPosition="before"
                            disabled={!submitUserInfoEnable}
                            primary={submitUserInfoEnable}
                            onClick={(e) => {
                                this.setState({checkPass: true});
                            }}
                        /> : null}
                    </CardText>
                    {editUserInfo ? null :
                        <TextField
                            floatingLabelText='账户地址'
                            floatingLabelFixed={true}
                            fullWidth={true}
                            disabled={true}
                            value={item.account_address ? item.account_address : ''}
                        />}
                    {editUserInfo ? null :
                        <TextField
                            floatingLabelText='认证日期'
                            floatingLabelFixed={true}
                            fullWidth={true}
                            disabled={true}
                            value={item.createdAt ? item.createdAt.toLocaleString() : ''}
                        />
                    }
                    {editUserInfo ? null :
                        <RaisedButton
                            icon={<ActionAccountCircle/>}
                            label="查看证书"
                            primary={true}
                            style={{padding: 10, marginTop: 10}}
                            fullWidth={true}
                            onClick={() => {
                                db.table('user_cert').where({user_tel: this.props.openItem.phone}).first().then((res) => {
                                    this.setState({openCert: true, cert: res})
                                });
                            }}
                        />
                    }
                    {editUserInfo ? null :
                        <div>
                            <RaisedButton
                                icon={<ActionDownload/>}
                                label="下载证书"
                                primary={true}
                                fullWidth={true}
                                style={{padding: 10}}
                                onClick={() => {
                                    // window.location.href= 'http://'+window.location.host + "/certdownload";
                                    let eleLink = document.createElement('a');
                                    eleLink.download = this.props.openItem.phone + '.cert';
                                    eleLink.style.display = 'none';
                                    var blob = new Blob([this.props.openItem.user_certificate_pem]);
                                    eleLink.href = URL.createObjectURL(blob);
                                    document.body.appendChild(eleLink);
                                    eleLink.click();
                                    document.body.removeChild(eleLink);
                                }}/>
                            <RaisedButton
                                icon={<ActionDownload/>}
                                label="下载私钥"
                                primary={true}
                                fullWidth={true}
                                style={{padding: 10}}
                                onClick={() => {
                                    let eleLink = document.createElement('a');
                                    eleLink.download = this.props.openItem.phone + '.prvkey';
                                    eleLink.style.display = 'none';
                                    var blob = new Blob([this.props.openItem.prv_key_pem_encrypted]);
                                    eleLink.href = URL.createObjectURL(blob);
                                    document.body.appendChild(eleLink);
                                    eleLink.click();
                                    document.body.removeChild(eleLink);
                                }}/>
                        </div>
                    }

                    {editUserInfo ? null :
                        <RaisedButton
                            icon={<ActionEdit/>}
                            label="密码修改"
                            primary={true}
                            fullWidth={true}
                            style={{padding: 10}}
                            onTouchTap={e => this.setState({mod_pass: true})}/>
                    }
                    <Snackbar
                        open={snack_bar}
                        message={this.renderChip()}
                        autoHideDuration={2000}
                        bodyStyle={{backgroundColor: 'rgba(47,47,47,0.7)', height: 'auto', textAlign: 'center'}}
                        contentStyle={{height: 80, display: 'inline-block'}}
                        onRequestClose={(reason) => {
                            this.setState({snack_bar: !snack_bar});
                            //browserHistory.push();
                            //browserHistory.push('/');
                        }}
                    />
                </Card>

                <Dialog
                    title="用户信息修改提醒"
                    actions={actionUserInfo}
                    modal={false}
                    open={this.state.checkPass}
                    onRequestClose={() => {
                        this.setState({checkPass: false})
                    }}
                >
                    <Divider style={{border: '1px dashed', marginTop: 2}}/>
                    请注意:<br/>
                    1. 一旦提交修改成功，请向管理员提交修改后的信息<br/>
                    2. 信息更新期间可能会对操作带来不便，敬请谅解。
                    <Divider style={{border: '1px dashed', marginBottom: 30}}/>
                    <p style={{color: red700}}>*输入私钥密码:</p>
                    <TextField
                        type='password'
                        floatingLabelText='私钥密码'
                        floatingLabelStyle={{color: blue400}}
                        errorText={this.state.pass_err}
                        hintText='输入密码'
                        onChange={(e, newValue) => {
                            if (newValue === '')
                                this.setState({confirmUserInfo: false, update_pass: newValue, pass_err: '密码不可为空'});
                            else
                                this.setState({confirmUserInfo: true, update_pass: newValue, pass_err: ''});
                        }}
                    />
                </Dialog>
                <Drawer width={this.state.openAccount ? this.state.cw : 0}
                        containerStyle={{position: 'fixed', top: 0, overflowY: 'hidden'}}
                        openSecondary={true} open={this.state.openAccount}>
                    {this.renderCreateBy()}
                </Drawer>

                <Drawer width={this.state.openCert ? this.state.cw : 0}
                        containerStyle={{position: 'fixed', top: 0, overflowY: 'hidden'}}
                        openSecondary={true} open={this.state.openCert}>
                    {this.renderMyCert()}
                </Drawer>
                <Drawer width={this.state.mod_pass ? this.state.cw : 0}
                        containerStyle={{position: 'fixed', top: 0, overflowY: 'hidden'}}
                        openSecondary={true} open={this.state.mod_pass}>
                    {this.renderModPwd()}
                </Drawer>
            </div>
        );
    }
}

Tab2Detail.propTypes = {
};

export default createContainer((props) => {
    //可以传递uid,也可以准备好数据之后直接传递openItem
    if (!props.uid) {
        return {openItem: props.openItem || {}};
    }
    else {
        let openItem = Session.get("curUser");
        db.table('user_cert').where({user_tel: openItem.phone}).first().then((res) => {
            if (!res) {
                let cert = openItem.user_certificate_pem;
                let c = new X509();
                c.readCertPEM(cert);
                let cert_info = {
                    user_tel: openItem.phone,
                    serial_number: c.getSerialNumberHex(),
                    signature_algorithm: c.getSignatureAlgorithmName(),
                    issuer: c.getIssuerString(),
                    not_before: zulutodate(c.getNotBefore()),
                    not_after: zulutodate(c.getNotAfter()),
                    subject: c.getSubjectString(),
                    key_algorithm: c.getSignatureAlgorithmField(),
                    signature: c.getSignatureValueHex(),
                };
                console.log('cert_info:' + cert_info);
                db.table('user_cert').add(cert_info).then((id) => {
                    console.log('add item success ' + id)
                })
            }
        });
        return {
            openItem: openItem ? openItem : {}
        }
    }
}, Tab2Detail);
